<!DOCTYPE html>
<html>
<body>
    <h1>SSE 客户端示例</h1>
    <div>
        <input type="text" id="messageInput" placeholder="输入消息..." style="width: 300px;" />
        <button id="sendButton">发送</button>
    </div>
    <div id="events" style="margin-top: 20px; white-space: pre-wrap;"></div>

    <script>
        let eventSource = null;
        const sendButton = document.getElementById('sendButton');
        const messageInput = document.getElementById('messageInput');
        const eventsDiv = document.getElementById('events');
        
        sendButton.addEventListener('click', () => {
            const message = messageInput.value.trim();
            if (!message) {
                alert('请输入消息');
                return;
            }
            
            // 禁用按钮防止重复发送
            sendButton.disabled = true;
            messageInput.disabled = true;
            
            // 清空之前的内容
            eventsDiv.innerHTML = '';
            
            // 创建新的 SSE 连接
            eventSource = new EventSource(`http://localhost:8080/langchain4j/stream?message=${encodeURIComponent(message)}`);
            
            eventSource.onmessage = (e) => {
                console.log("收到数据:", e.data, "事件ID:", e.lastEventId);
                eventsDiv.innerHTML += e.data;
                
                // 检查是否接收完成（假设服务端发送 "[DONE]" 表示结束）
                if (e.data.includes('[DONE]')) {
                    closeConnection();
                }
            };
            
            eventSource.onerror = (e) => {
                console.error("SSE 错误:", e);
                closeConnection();
            };
        });
        
        function closeConnection() {
            if (eventSource) {
                eventSource.close();
                eventSource = null;
            }
            sendButton.disabled = false;
            messageInput.disabled = false;
        }
    </script>
</body>
</html>